package com.guodexian.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
/**
 * @author Administrator
 */
@Configuration
@ComponentScan("com.guodexian")
@MapperScan(basePackages = "com.guodexian.mapper")
@PropertySource("classpath:application.properties")
public class MyBatisConfig {
    @Bean
    public org.apache.ibatis.session.Configuration configuration() {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //开启下划线到驼峰的映射
        configuration.setMapUnderscoreToCamelCase(true);
        return configuration;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource,org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setConfiguration(configuration);
        return factoryBean.getObject();
    }
    @Bean
    public DataSource dataSource(@Value("${spring.datasource.driver}") String  driver,
                                 @Value("${spring.datasource.url}")String url,
                                 @Value("${spring.datasource.username}") String username,
                                 @Value("${spring.datasource.password}") String pass
    ) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(pass);
        return dataSource;
    }
}